package com.xunua.myaudioandvideolearning

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import java.io.File

class MainActivity : AppCompatActivity() {
    private var h264player:H264player?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getPermission()
        initSurface()
    }

    //控件surfaceView是画框（放surface的）     surface 画布（内容在surface里面）
    private fun initSurface() {
        var surfaceView = findViewById<SurfaceView>(R.id.preview)
        surfaceView.holder.addCallback(object:SurfaceHolder.Callback{
            override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
                //一帧I帧情况下无法显示画面是因为解码器规范不一样，传输缓冲区的大小不一致，缓冲区还没到刷新的时候，所以一个I帧并不会显示画面。需要多拷贝几帧才能出来画面。
                h264player= H264player(File(Environment.getExternalStorageDirectory(),"codec.h264").absolutePath,surfaceHolder.surface)
                h264player?.play()
//                surface
//                "/sdcard/1frame.h264"
            }

            override fun surfaceChanged(surfaceHolder: SurfaceHolder, p1: Int, p2: Int, p3: Int) {

            }

            override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) {

            }

        })
    }

    private fun getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(
                arrayOf(
                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                ), 1
            )
        }
    }
}